#!/usr/bin/env python3
"""
Script to split hierarchical_cooperation_paper.tex into modular structure.

Structure:
- sections/01_intro_model.tex: Introduction + System Model
- sections/02_mechanics_coordination.tex: Statistical Mechanics + Coordination Mechanisms
- sections/03_validation_discussion.tex: Empirical Validation + Discussion + Conclusion
- sections/04_appendices.tex: All appendices and acknowledgements
"""

import os
import re
from pathlib import Path

def read_file(filepath):
    """Read the LaTeX file."""
    with open(filepath, 'r', encoding='utf-8') as f:
        return f.read()

def write_file(filepath, content):
    """Write content to file."""
    os.makedirs(os.path.dirname(filepath), exist_ok=True)
    with open(filepath, 'w', encoding='utf-8') as f:
        f.write(content)
    print(f"✓ Created: {filepath}")

def extract_lines_by_range(lines, start_line, end_line):
    """Extract lines from start_line (inclusive) to end_line (exclusive)."""
    return lines[start_line:end_line]

def find_section_line(lines, section_marker):
    """Find the line number where a section starts."""
    for i, line in enumerate(lines):
        if section_marker in line:
            return i
    return -1

def extract_preamble_and_abstract(lines, intro_line):
    """Extract everything before Introduction section."""
    return lines[:intro_line]

def create_main_file(preamble_lines, output_dir):
    """Create the new main file that includes the split sections."""

    # Join preamble lines
    preamble = '\n'.join(preamble_lines)

    main_content = f"""{preamble}

% Section 1-2: Introduction and System Model
\\input{{sections/01_intro_model}}

% Section 3-4: Statistical Mechanics and Coordination Mechanisms
\\input{{sections/02_mechanics_coordination}}

% Section 5-7: Empirical Validation, Discussion, and Conclusion
\\input{{sections/03_validation_discussion}}

% Appendices and Acknowledgements
\\input{{sections/04_appendices}}

\\end{{document}}
"""

    write_file(f"{output_dir}/hierarchical_cooperation_paper_modular.tex", main_content)
    return main_content

def split_paper(input_file, output_dir):
    """Main function to split the paper."""

    print("=" * 70)
    print("Splitting Hierarchical Cooperation Paper")
    print("=" * 70)

    # Read the original file as lines
    with open(input_file, 'r', encoding='utf-8') as f:
        lines = f.readlines()

    # Create sections directory
    sections_dir = f"{output_dir}/sections"
    os.makedirs(sections_dir, exist_ok=True)

    # Find all section markers (line numbers are 0-indexed)
    print("\nFinding section boundaries...")
    intro_line = find_section_line(lines, r'\section{Introduction}')
    system_model_line = find_section_line(lines, r'\section{System Model}')
    stat_mech_line = find_section_line(lines, r'\section{Statistical Mechanics Perspective}')
    coord_line = find_section_line(lines, r'\section{Coordination Mechanisms}')
    validation_line = find_section_line(lines, r'\section{Empirical Validation}')
    discussion_line = find_section_line(lines, r'\section{Discussion and Outlook}')
    conclusion_line = find_section_line(lines, r'\section{Conclusion}')
    appendix_line = find_section_line(lines, r'\appendix')
    biblio_line = find_section_line(lines, r'\printbibliography')

    print(f"  Introduction: line {intro_line}")
    print(f"  System Model: line {system_model_line}")
    print(f"  Statistical Mechanics: line {stat_mech_line}")
    print(f"  Coordination: line {coord_line}")
    print(f"  Validation: line {validation_line}")
    print(f"  Discussion: line {discussion_line}")
    print(f"  Conclusion: line {conclusion_line}")
    print(f"  Appendix: line {appendix_line}")
    print(f"  Bibliography: line {biblio_line}")

    # Extract sections
    print("\nExtracting sections...")

    # Preamble and abstract (everything before Introduction)
    preamble_lines = extract_preamble_and_abstract(lines, intro_line)

    # File 1: Introduction + System Model (Sections 1-2)
    print("\n[1/4] Extracting Introduction and System Model...")
    file1_lines = extract_lines_by_range(lines, intro_line, stat_mech_line)
    file1_content = f"""% Introduction and System Model
% Sections 1-2 of Hierarchical Cooperation Paper

{''.join(file1_lines)}"""
    write_file(f"{sections_dir}/01_intro_model.tex", file1_content)

    # File 2: Statistical Mechanics + Coordination Mechanisms (Sections 3-4)
    print("\n[2/4] Extracting Statistical Mechanics and Coordination Mechanisms...")
    file2_lines = extract_lines_by_range(lines, stat_mech_line, validation_line)
    file2_content = f"""% Statistical Mechanics Perspective and Coordination Mechanisms
% Sections 3-4 of Hierarchical Cooperation Paper

{''.join(file2_lines)}"""
    write_file(f"{sections_dir}/02_mechanics_coordination.tex", file2_content)

    # File 3: Empirical Validation + Discussion + Conclusion (Sections 5-7)
    print("\n[3/4] Extracting Empirical Validation, Discussion, and Conclusion...")
    file3_lines = extract_lines_by_range(lines, validation_line, appendix_line)
    file3_content = f"""% Empirical Validation, Discussion and Outlook, Conclusion
% Sections 5-7 of Hierarchical Cooperation Paper

{''.join(file3_lines)}"""
    write_file(f"{sections_dir}/03_validation_discussion.tex", file3_content)

    # File 4: Appendices + Acknowledgements (everything from \appendix to \printbibliography)
    print("\n[4/4] Extracting Appendices and Acknowledgements...")
    file4_lines = extract_lines_by_range(lines, appendix_line, biblio_line)
    file4_content = f"""% Appendices and Acknowledgements
% All appendix sections of Hierarchical Cooperation Paper

{''.join(file4_lines)}"""
    write_file(f"{sections_dir}/04_appendices.tex", file4_content)

    # Create the new main file
    print("\n[Main] Creating modular main file...")
    create_main_file(preamble_lines, output_dir)

    # Create README for the sections
    readme_content = """# Hierarchical Cooperation Paper - Modular Structure

This directory contains the split sections of the hierarchical cooperation paper.

## File Structure

- `01_intro_model.tex` - Introduction and System Model (Sections 1-2)
  * Introduction with 5 contributions
  * System Model with formal definitions
  * Continuous-Time Formulation (master equations)
  * Stability Guarantees (spectral theory)

- `02_mechanics_coordination.tex` - Statistical Mechanics and Coordination (Sections 3-4)
  * Statistical Mechanics Perspective
  * Phase Transitions and Critical Behavior
  * Universality Classes (4 classes)
  * Early Warning Indicators
  * Coordination Mechanisms (4 mechanisms)

- `03_validation_discussion.tex` - Validation and Conclusions (Sections 5-7)
  * Empirical Validation
  * Simulation Framework
  * Experimental Protocol
  * Case Study Results
  * Discussion and Outlook
  * Conclusion

- `04_appendices.tex` - All Appendices and Acknowledgements
  * Appendix A: Spectral Stability Proof
  * Appendix B: Master Equation Well-Posedness
  * Appendix C: Information-Thermodynamic Duality
  * Appendix D: Thermodynamic Transitions and Variance Dynamics
  * Appendix E: Renormalization Group Derivation
  * Appendix F: Early Warning Indicators
  * Acknowledgements

## Usage

The main file `hierarchical_cooperation_paper_modular.tex` includes all sections via `\\input{}` commands.

To compile:
```bash
cd ..
xelatex hierarchical_cooperation_paper_modular.tex
biber hierarchical_cooperation_paper_modular
xelatex hierarchical_cooperation_paper_modular.tex
xelatex hierarchical_cooperation_paper_modular.tex
```

## Benefits of Modular Structure

1. **Easier collaboration** - Different authors can work on different sections
2. **Version control** - Cleaner git diffs for specific sections
3. **Maintainability** - Easier to locate and edit specific content
4. **Reusability** - Sections can be reused in other documents
5. **Compilation speed** - Can compile individual sections for quick checks
"""

    write_file(f"{sections_dir}/README.md", readme_content)

    # Print summary
    print("\n" + "=" * 70)
    print("Split Complete!")
    print("=" * 70)
    print(f"\nOutput directory: {output_dir}")
    print(f"\nFiles created:")
    print(f"  ├── hierarchical_cooperation_paper_modular.tex (main file)")
    print(f"  └── sections/")
    print(f"      ├── 01_intro_model.tex")
    print(f"      ├── 02_mechanics_coordination.tex")
    print(f"      ├── 03_validation_discussion.tex")
    print(f"      ├── 04_appendices.tex")
    print(f"      └── README.md")

    # Get file sizes
    import glob
    sizes = []
    for i in range(1, 5):
        fname = f"{sections_dir}/0{i}_*.tex"
        files = glob.glob(fname)
        if files:
            size = os.path.getsize(files[0])
            sizes.append(size)

    print(f"\nSection file sizes:")
    labels = ["Intro+Model", "Mechanics+Coord", "Validation+Discussion", "Appendices"]
    for i, (label, size) in enumerate(zip(labels, sizes), 1):
        print(f"  File {i} ({label:20s}): {size:>8,} bytes ({size/1024:.1f} KB)")

    print(f"\nTo compile the modular version:")
    print(f"  cd {output_dir}")
    print(f"  xelatex hierarchical_cooperation_paper_modular.tex")
    print(f"  biber hierarchical_cooperation_paper_modular")
    print(f"  xelatex hierarchical_cooperation_paper_modular.tex")
    print(f"  xelatex hierarchical_cooperation_paper_modular.tex")
    print("\n" + "=" * 70)

if __name__ == "__main__":
    # Configuration
    base_dir = "/home/linden/claude/cursor/claude-code-theory/hierarchical_cooperation_book_v2"
    input_file = f"{base_dir}/hierarchical_cooperation_paper.tex"
    output_dir = f"{base_dir}"  # Output in same directory

    # Run the split
    split_paper(input_file, output_dir)
